package com.hgyc.mom.mes.service.impl;

import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hgyc.mom.common.exception.BizException;
import com.hgyc.mom.mes.entity.MesRouting;
import com.hgyc.mom.mes.entity.MesRoutingProcess;
import com.hgyc.mom.mes.entity.MesRoutingProduct;
import com.hgyc.mom.mes.enums.ProcessRoutingStatusEnum;
import com.hgyc.mom.mes.mapper.MesRoutingMapper;
import com.hgyc.mom.mes.service.MesRoutingProcessService;
import com.hgyc.mom.mes.service.MesRoutingProductService;
import com.hgyc.mom.mes.service.MesRoutingService;
import com.hgyc.mom.mes.vo.MesRoutingVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import java.util.List;

/**
 * 工艺路线Service业务层实现
 *
 * @author fwj
 * @since 2025-07-01
 */
@Slf4j
@Service
public class MesRoutingServiceImpl extends ServiceImpl<MesRoutingMapper, MesRouting> implements MesRoutingService {

    @Autowired
    private MesRoutingProcessService mesRoutingProcessService;
    @Autowired
    private MesRoutingProductService mesRoutingProductService;
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void saveRouting(MesRoutingVO mesRoutingVO) {
        mesRoutingVO.setStatus(ProcessRoutingStatusEnum.DRAFT.getValue());
        save(mesRoutingVO);

        //新增工艺组成
        List<MesRoutingProcess> addProcess = mesRoutingVO.getAddProcess();
        if (!CollectionUtils.isEmpty(addProcess)) {
            addProcess.forEach(item -> {
                item.setId(null);
                item.setRoutingId(mesRoutingVO.getId());
            });
            mesRoutingProcessService.saveBatch(addProcess);
        }
        // 依次填充 nextProcessId
        if (addProcess.size() > 1) {
            for (int i = 0; i < addProcess.size() - 1; i++) {
                MesRoutingProcess current = addProcess.get(i);
                MesRoutingProcess next = addProcess.get(i + 1);
                current.setNextProcessId(next.getId());
            }
            mesRoutingProcessService.updateBatchById(addProcess);
        }

        // 批量更新 nextProcessId
        mesRoutingProcessService.updateBatchById(addProcess);

        //新增工艺路线关联产品
        List<MesRoutingProduct> products = mesRoutingVO.getAddProducts();
        if (!CollectionUtils.isEmpty(products)) {
            products.forEach(item -> {
                item.setId(null);
                item.setRoutingId(mesRoutingVO.getId());
            });
            mesRoutingProductService.saveBatch(products);
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void updateRouting(MesRoutingVO mesRoutingVO) {
        updateById(mesRoutingVO);

        //删除工艺组成
        if (!CollectionUtils.isEmpty(mesRoutingVO.getDeleteProcessIds())) {
            mesRoutingProcessService.removeBatchByIds(mesRoutingVO.getDeleteProcessIds());
        }

        //新增工艺组成
        List<MesRoutingProcess> addProcess = mesRoutingVO.getAddProcess();
        if (!CollectionUtils.isEmpty(addProcess)) {
            addProcess.forEach(item -> {
                item.setId(null);
                item.setRoutingId(mesRoutingVO.getId());
            });
            mesRoutingProcessService.saveBatch(addProcess);
        }

        //更新工艺组成
        if (!CollectionUtils.isEmpty(mesRoutingVO.getUpdateProcess())) {
            List<MesRoutingProcess> updateProcess = mesRoutingVO.getUpdateProcess();
            mesRoutingProcessService.updateBatchById(updateProcess);
        }

        //更新工艺路线nextProcessId
        List<MesRoutingProcess> routingProcessList = mesRoutingProcessService.getByParentId(mesRoutingVO.getId());
        if (routingProcessList.size() > 1) {
            for (int i = 0; i < routingProcessList.size() - 1; i++) {
                MesRoutingProcess current = routingProcessList.get(i);
                MesRoutingProcess next = routingProcessList.get(i + 1);
                current.setNextProcessId(next.getId());
            }
            mesRoutingProcessService.updateBatchById(routingProcessList);
        }

        //删除工艺路线关联产品
        if (!CollectionUtils.isEmpty(mesRoutingVO.getDeleteProductIds())) {
            mesRoutingProductService.removeBatchByIds(mesRoutingVO.getDeleteProductIds());
        }

        //新增工艺路线关联产品
        List<MesRoutingProduct> products = mesRoutingVO.getAddProducts();
        if (!CollectionUtils.isEmpty(products)) {
            products.forEach(item -> {
                item.setId(null);
                item.setRoutingId(mesRoutingVO.getId());
            });
            mesRoutingProductService.saveBatch(products);
        }

        //更新工艺路线关联产品
        if (!CollectionUtils.isEmpty(mesRoutingVO.getUpdateProducts())) {
            List<MesRoutingProduct> updateProducts = mesRoutingVO.getUpdateProducts();
            mesRoutingProductService.updateBatchById(updateProducts);
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void removeRouting(List<Long> ids) {
        // TODO 其他逻辑
        removeByIds(ids);
        //删除工艺组成
        mesRoutingProcessService.deleteBatchByParentIds(ids);
        //删除工艺路线关联产品
        mesRoutingProductService.deleteBatchByParentIds(ids);
    }

    @Override
    public void updateStatus(String status, List<Long> ids) {
        LambdaUpdateWrapper<MesRouting> updateWrapper = Wrappers.lambdaUpdate();
        updateWrapper.set(MesRouting::getStatus, status);
        updateWrapper.in(MesRouting::getId, ids);
        baseMapper.update(updateWrapper);
    }

    @Override
    public List<MesRouting> getProductRouting(Long productId) {
        return baseMapper.getProductRouting(productId);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public String importData(List<MesRouting> mesRoutingList, boolean updateSupport) {
        if (mesRoutingList == null || mesRoutingList.isEmpty()) {
            throw new IllegalArgumentException("导入数据不能为空");
        }

        try {
            if (updateSupport) {
                // TODO 实现更新已有数据的导入逻辑
                return "更新导入成功，共导入 " + mesRoutingList.size() + " 条数据";
            } else {
                // TODO 实现不更新已有数据的导入逻辑
                return "新增导入成功，共导入 " + mesRoutingList.size() + " 条数据";
            }
        } catch (Exception e) {
            log.error("工艺路线导入失败", e);
            throw new BizException("工艺路线导入失败：" + e.getMessage());
        }
    }
}